package com.esperia09.webservice.mixiVoiceNotify;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.esperia09.webservice.mixiVoiceNotify.common.SendRequest;

public class RefreshAccessToken extends HttpServlet {
	private static final String FOR_GET_TOKEN_URL = "https://secure.mixi-platform.com/2/token";
	// private static final String OAUTH_AFTER_REDIRECT_URL = "http%3A%2F%2Fmixi-voice-notify.appspot.com%2Fcallback.jsp"; // 
	private static final String OAUTH_AFTER_REDIRECT_URL = "http%3A%2F%2Flocalhost:8888%2Fcallback.jsp"; // local

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("application/json");
		
		String refreshToken = req.getParameter("refresh_token");
		String tokenStr = refreshAccessToken(refreshToken);
		resp.getWriter().println(tokenStr);
	}
	/**
	 * mixiにAccessToken/RefreshTokenをリクエストする
	 * @param authCode
	 * @return
	 * @throws IOException
	 */
	public static String refreshAccessToken(String refreshToken) throws IOException {
		if(refreshToken == null) {
			return "{}";
		}
		
		HttpURLConnection con = null;
		String result = "{}";
		try {
		    URL url = new URL(FOR_GET_TOKEN_URL);
		    con = (HttpURLConnection) url.openConnection();
		    con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");

		    String postString = "grant_type=refresh_token"
		    	+ "&client_id=" + GetOAuthKeys.getMixiConsumerKey()
		    	+ "&client_secret=" + GetOAuthKeys.getMixiConsumerSecret()
		    	+ "&refresh_token=" + refreshToken;
		    
		    result = SendRequest.sendPost(con, postString);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
		    if (con != null) con.disconnect();
		}
		
		return result;
	}
}
